// ==================== 主页脚本 ====================

// API配置
const API_BASE_URL = 'http://localhost:3000/api';

// DOM元素
const elements = {
    systemAnnouncement: document.getElementById('systemAnnouncement')
};

// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 百日行动线索收集系统 - 主页加载完成');

    // 初始化页面
    initializePage();

    // 加载系统设置
    loadSystemSettings();

    // 初始化滚动动画
    initializeScrollAnimations();

    // 初始化页面过渡效果
    initializePageTransitions();
});

// ==================== 页面初始化 ====================
function initializePage() {
    // 添加页面加载动画
    document.body.classList.add('page-transition');

    // 延迟移除加载效果
    setTimeout(() => {
        document.body.classList.add('loaded');
    }, 100);

    // 初始化平滑滚动
    initializeSmoothScroll();

    // 初始化导航栏效果
    initializeNavbar();
}

// ==================== 加载系统设置 ====================
async function loadSystemSettings() {
    try {
        const response = await fetch(`${API_BASE_URL}/system-settings`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            const result = await response.json();
            const settings = result.data;

            // 更新系统公告
            if (settings.system_announcement) {
                updateSystemAnnouncement(settings.system_announcement);
            }

            // 更新页面标题
            if (settings.site_title) {
                document.title = settings.site_title;
                updatePageTitle(settings.site_title);
            }

            console.log('✅ 系统设置加载成功');
        } else {
            console.warn('⚠️ 系统设置加载失败，使用默认配置');
        }
    } catch (error) {
        console.error('❌ 加载系统设置时出错:', error);
    }
}

// ==================== 更新系统公告 ====================
function updateSystemAnnouncement(announcement) {
    if (elements.systemAnnouncement) {
        elements.systemAnnouncement.textContent = announcement;

        // 如果公告为空，隐藏公告区域
        const announcementSection = elements.systemAnnouncement.closest('.announcement-section');
        if (!announcement.trim() && announcementSection) {
            announcementSection.style.display = 'none';
        }
    }
}

// ==================== 更新页面标题 ====================
function updatePageTitle(title) {
    // 更新导航栏品牌名称
    const navbarBrand = document.querySelector('.navbar-brand');
    if (navbarBrand) {
        const icon = navbarBrand.querySelector('i');
        navbarBrand.innerHTML = '';
        if (icon) {
            navbarBrand.appendChild(icon.cloneNode(true));
        }
        navbarBrand.innerHTML += ` ${title}`;
    }

    // 更新主标题
    const mainTitle = document.querySelector('.hero-content h1');
    if (mainTitle) {
        const icon = mainTitle.querySelector('i');
        const titleText = title.replace('系统', '');
        mainTitle.innerHTML = '';
        if (icon) {
            mainTitle.appendChild(icon.cloneNode(true));
        }
        mainTitle.innerHTML += ` ${titleText}`;
    }
}

// ==================== 平滑滚动 ====================
function initializeSmoothScroll() {
    // 为所有锚点链接添加平滑滚动
    const links = document.querySelectorAll('a[href^="#"]');

    links.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');

            // 忽略空锚点
            if (href === '#') return;

            const target = document.querySelector(href);
            if (target) {
                e.preventDefault();

                const offsetTop = target.offsetTop - 70; // 考虑导航栏高度

                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });

                // 更新URL但不触发滚动
                history.pushState(null, null, href);
            }
        });
    });
}

// ==================== 导航栏效果 ====================
function initializeNavbar() {
    const navbar = document.querySelector('.navbar');

    if (!navbar) return;

    // 滚动时改变导航栏样式
    window.addEventListener('scroll', function() {
        if (window.scrollY > 50) {
            navbar.classList.add('navbar-scrolled');
        } else {
            navbar.classList.remove('navbar-scrolled');
        }
    });

    // 添加CSS样式
    const style = document.createElement('style');
    style.textContent = `
        .navbar-scrolled {
            background-color: rgba(0, 123, 255, 0.95) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
    `;
    document.head.appendChild(style);
}

// ==================== 滚动动画 ====================
function initializeScrollAnimations() {
    // 创建Intersection Observer
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate');
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    // 观察需要动画的元素
    const animateElements = document.querySelectorAll('.feature-card, .process-step, .hero-content, .hero-image');
    animateElements.forEach(el => {
        observer.observe(el);
    });

    // 添加动画CSS
    const style = document.createElement('style');
    style.textContent = `
        .feature-card, .process-step {
            opacity: 0;
            transform: translateY(30px);
            transition: opacity 0.6s ease, transform 0.6s ease;
        }
        
        .feature-card.animate, .process-step.animate {
            opacity: 1;
            transform: translateY(0);
        }
        
        .feature-card:nth-child(1).animate { transition-delay: 0.1s; }
        .feature-card:nth-child(2).animate { transition-delay: 0.2s; }
        .feature-card:nth-child(3).animate { transition-delay: 0.3s; }
        .feature-card:nth-child(4).animate { transition-delay: 0.4s; }
        
        .process-step:nth-child(1).animate { transition-delay: 0.1s; }
        .process-step:nth-child(2).animate { transition-delay: 0.3s; }
        .process-step:nth-child(3).animate { transition-delay: 0.5s; }
    `;
    document.head.appendChild(style);
}

// ==================== 页面过渡效果 ====================
function initializePageTransitions() {
    // 为页面链接添加过渡效果
    const pageLinks = document.querySelectorAll('a[href$=".html"]');

    pageLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');

            // 如果是外部链接，不处理
            if (this.hostname !== window.location.hostname) return;

            e.preventDefault();

            // 添加页面离开动画
            document.body.classList.add('page-leaving');

            // 延迟跳转
            setTimeout(() => {
                window.location.href = href;
            }, 300);
        });
    });

    // 添加过渡CSS
    const style = document.createElement('style');
    style.textContent = `
        .page-leaving {
            opacity: 0;
            transform: translateY(-20px);
            transition: opacity 0.3s ease, transform 0.3s ease;
        }
    `;
    document.head.appendChild(style);
}

// ==================== 工具函数 ====================

// 显示消息提示
function showMessage(message, type = 'info', duration = 3000) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';

    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alertDiv);

    // 自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.classList.remove('show');
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    document.body.removeChild(alertDiv);
                }
            }, 150);
        }
    }, duration);
}

// 格式化日期
function formatDate(date) {
    if (!date) return '';

    const d = new Date(date);
    return d.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// ==================== 错误处理 ====================
window.addEventListener('error', function(e) {
    console.error('页面出现错误:', e.error);
});

window.addEventListener('unhandledrejection', function(e) {
    console.error('未处理的Promise错误:', e.reason);
});

// ==================== 导出给其他脚本使用 ====================
window.HunActionApp = {
    API_BASE_URL,
    showMessage,
    formatDate,
    formatFileSize,
    debounce,
    throttle
};
